<?php

namespace dingdong\model;

class BaseModel
{
    protected $db = null;

    public function __construct($db)
    {
        $this->db = $db;
    }

    public function queryOne($sql)
    {
        try {

            $dbObj = $this->db->get();
            $statement = $dbObj->query($sql);
            $result = $statement->fetchAll();
            $this->db->put($dbObj);

            if (!empty($result)) {
                return $result['0'];
            }
            return $result;
        } catch (\Exception $e) {
            var_dump('数据库执行出错: ' . $e->getMessage());
        }
    }

    public function queryAll($sql)
    {
        try {

            $dbObj = $this->db->get();
            $statement = $dbObj->query($sql);
            $result = $statement->fetchAll();

            $this->db->put($dbObj);

            return $result;
        } catch (\Exception $e) {

            var_dump('数据库执行出错: ' . $e->getMessage());
        }
    }

    public function query($sql)
    {

        try {

            $dbObj = $this->db->get();
            $dbObj->query($sql);

            $this->db->put($dbObj);
        } catch (\Exception $e) {

            var_dump('数据库执行出错: ' . $e->getMessage());
        }
    }

    public function insertGetId($sql)
    {

        try {

            $dbObj = $this->db->get();
            $dbObj->query($sql);
            $this->db->put($dbObj);

            return $dbObj->lastInsertId();
        } catch (\Exception $e) {

            var_dump('数据库执行出错: ' . $e->getMessage());
        }
    }
}